﻿Public Class Login
    Inherits System.Web.UI.Page

    Private Sub Login_Load(sender As Object, e As System.EventArgs) Handles Me.Load

        If Me.IsPostBack = False Then Me.Session.Remove("LoggedUser")

        Me.SetFocus("MainContent_LoginUser_UserName")


    End Sub

    Private Sub LoginUser_LoggedIn(sender As Object, e As System.EventArgs) Handles LoginUser.LoggedIn

        'Dim user As MembershipUser = Membership.GetUser(LoginUser.UserName)
        Dim db As New DbHelper

        'Code before
        'Dim u As UserType = db.GetUserByName(user.UserName)
        'Replaced with
        Dim u As UserType = db.GetUserByName(LoginUser.UserName)

        If u Is Nothing Then
            'Addup user without any rights
            u = New UserType
            With u
                .UserId = Guid.NewGuid
                '.ProviderUserKey = user.ProviderUserKey.ToString
                .UserName = LoginUser.UserName
            End With
            db.AddUser(u)
            'Else
            '    If u.ProviderUserKey = "" Then
            '        'update the provider user key
            '        u.ProviderUserKey = user.ProviderUserKey.ToString
            '        db.UpdateUser(u)
            '    End If
        End If

        If u Is Nothing Then
            Throw New AccessViolationException("Authentication error")
        Else
            Me.Session("LoggedUser") = u
            Me.Response.Redirect("AccessRecords.aspx")
        End If

    End Sub

    Private Sub LoginUser_LoggingIn(sender As Object, e As System.Web.UI.WebControls.LoginCancelEventArgs) Handles LoginUser.LoggingIn
        PerformBuiltInLogin()
    End Sub

    Private Sub PerformBuiltInLogin()

        If Debugger.IsAttached Then
            If Me.LoginUser.UserName = "admin" AndAlso Me.LoginUser.Password = "admin" Then
                Dim db As New DbHelper
                Dim u As UserType = db.GetUserByName(Me.LoginUser.UserName)
                If u IsNot Nothing Then
                    Me.Session("LoggedUser") = u
                    Me.Response.Redirect("AccessRecords.aspx")
                End If
            End If
        End If

    End Sub

End Class